import { createRouter, createWebHistory } from 'vue-router';
import LayoutView from '../views/LayoutView.vue';
import LoginView from '../views/LoginView.vue';
import AdminView from '../views/AdminView.vue';
import NotFound from '../views/NotFound.vue';
import { CommonRoutes } from '../views/common';
import HomeView from '@/views/HomeView.vue';
import { UserRoutes } from '@/views/user';
import { userService } from '@/service';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { name: '登录', requireAuth: false  },
    },
    {
      path: '/admin',
      name: 'admin',
      component: AdminView,
      meta: { name: '登录', requireAuth: false },
    },
    {
      path: '/',
      name: 'index',
      component: LayoutView,
      redirect: () => ({ name: 'home' }),
      meta: { name: '首页', requireAuth: true },
      children: [
        {
          path: '',
          name: 'home',
          component: HomeView,
          meta: { name: '首页', requireAuth: true },
        },
        ...CommonRoutes,
        ...UserRoutes,
        {
          path: '/:pathMatch(.*)*',
          name: 'notfound',
          component: NotFound,
          meta: { name: '页面不存在', requireAuth: true },
        },
      ],
    },
  ],
});

// 添加导航守卫
router.beforeEach(async (to, from, next) => {
  // 检查要前往的路由是否需要认证
  const requireAuth = to.meta.requireAuth !== false;
  
  if (requireAuth) {
    // 需要认证的路由，检查登录状态
    const isLogin = await userService.check();
    if (!isLogin) {
      // 未登录，重定向到登录页
      next({ name: 'login' });
    } else {
      // 已登录，允许访问
      next();
    }
  } else {
    // 不需要认证的路由，直接允许访问
    next();
  }
});

export default router;
